<template >
	<div v-if="checkRole(['admin','root'])" v-loading="loading">
	   	<div id='line'></div>
    </div>
</template>
<script>
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
import { listDept} from "@/api/system/dept";//调用部门的接口去获取信息
import { listShow} from "@/api/show";//查询统计考勤记录
export default {
    name:'Show',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 日期字典，每个日期对应的数据下标
            dateDict:{},
            //部门列表
            deptList:[],
            //部门数据字典
            deptDict:{},
            //行政班级列表
            classList:[],
            //数据颜色列表
            corlorList:[],
            //数据列表
            dataList:[
                // {
                // name:'人工智能',
                // data:[80, 82, 88, 64, 50,60, 70, 85, 45, 92, 65, 62]
                // },
                // {
                // name:'计算机科学与技术',
                // data:[90, 80, 75, 85, 92, 65, 72, 80, 82, 91, 74, 80]
                // },
                // {
                // name:'电子信息工程',
                // data:[85.3, 82, 85, 75, 82, 91, 64, 80, 90, 80, 65, 82]
                // },
                // {
                // name:'物联网',
                // data:[88.3, 87, 65, 95, 72, 95, 74, 83, 91, 70, 75, 72]
                // },
                // {
                // name:'应用物理',
                // data:[69.3, 62, 75, 65, 87, 81, 74, 60, 83, 84, 76, 77]
                // },
                // {
                // name:'测控',
                // data:[75.3, 84, 82, 90, 88, 71, 84, 86, 70, 84, 85, 82]
                // }
            ],
            //时间数据列表，元素为时间(date)
            dateList:[]
            }
    },
    created() {
        this.getList();
    },
    methods:{
        //权限判断
        checkPermi,
        checkRole,
        //获取以当前时间为基准的年月日
        getDay(day){
            var today = new Date();
            var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
            today.setTime(targetday_milliseconds); //注意，这行是关键代码
            var tYear = today.getFullYear();
            var tMonth = today.getMonth();
            var tDate = today.getDate();
            tMonth = this.doHandleMonth(tMonth + 1);
            tDate = this.doHandleMonth(tDate);
            return tYear+"-"+tMonth+"-"+tDate;
        },
        doHandleMonth(month){
            var m = month;
            if(month.toString().length == 1){
            m = "0" + month;
            }
            return m;
        },
        //对比日期下标
        checkedDate(obj1,obj2,index,key1){
            index = index+1;
            //如果超长，就返回0
            if(index>this.dateList.length){
                return 0;
            }
            //如果日期匹配上了，则返回相应结果
            else if(obj1.shows[index].date===obj2.shows[key1].date){
                return ((obj2.shows[key1].mount/obj1.shows[index].mount)*100).toFixed(2);
            }
            else{
                this.checkedDate(obj1,obj2,index,key1);
            }
        },
        //随机生成颜色
        randomColor(){
        var color="";
        for(var i=0;i<3;i++) color+=parseInt(Math.random()*256)+",";
        //去除最后一个逗号
        color=color.substring(0,color.length-1);
        return color;
        },
        /** 查询部门列表 */
        getList() {
            this.loading = true;
            listDept().then(response => {
                this.deptList = response.data;
                for (const iterator of this.deptList) {
                    if(iterator.ancestors.length===9){
                        //得到行政班级列表
                        this.classList.push(iterator.deptId);
                        this.deptDict[iterator.deptId] = iterator.deptName;
                    }
                }
                return '获取部门id成功';
            }).then(response=>{
                let queryForm = {};
                queryForm.deptIds = this.classList;
                queryForm.startTime = this.getDay(-6);
                //获取往前七天的日期
                for(let i =-6;i<1;i++){
                    this.dateList.push(this.getDay(i));
                }
                //初始化颜色列表
                this.corlorList = [];
                for(let i = 0;i<this.dateList.length;i++){
                    this.dateDict[this.dateList[i]] = i;
                    this.corlorList.push(this.randomColor());
                }
                queryForm.endTime = this.getDay(1);
                listShow(queryForm).then(response=>{
                    // console.log(response);
                    let recordAllDataList = response.data[0];
                    let recordOkDataList = response.data[1];
                    //for in中  参数表示下标
                    for (const key in recordAllDataList) {
                        let obj = {};
                        //获取部门名称
                        obj.name = this.deptDict[recordAllDataList[key].deptId];
                        // 初始化数据的数组
                        obj.data = [];
                        //给数组日期字典的长度并赋值为0
                        for(let i = 0;i<this.dateList.length;i++){
                            obj.data.push(0);
                        }
                        
                        for (const key1 in recordOkDataList[key].shows) {
                            //如果当前记录的下标对应的日期不相等
                            let index = key1;
                            if(recordAllDataList[key].shows[index].date!=recordOkDataList[key].shows[key1].date){
                                obj.data[this.dateDict[recordOkDataList[key].shows[key1].date]] = this.checkedDate(recordAllDataList[key],recordOkDataList[key],index,key);
                            }
                            else{
                                /**
                                 * this.dateDict[recordAllDataList[key].shows[key1].date]
                                 * 这句代码的意思是：根据recordAllDataList[key].shows[key1].date获取日期字典的对应日期的下标
                                 * 也就对数据进行了赋值
                                 */
                                obj.data[this.dateDict[recordAllDataList[key].shows[key1].date]] = (((recordOkDataList[key].shows[key1].mount||0)/recordAllDataList[key].shows[key1].mount)*100).toFixed(2);
                            }
                        }
                        this.dataList.push(obj);
                    }
                    return '获取考勤数据成功'
            }).then(response =>{
                this.loading = false;
                const myChart = this.$echarts.init(document.getElementById("line"));
                //建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）
                window.addEventListener("resize", function() {
                    myChart.resize();
                });
                myChart.setOption((()=>{
                    let optionObj = {
                    backgroundColor: '#394056',
                    title: {
                    top: 10,
                    text: '出勤率统计',
                    x: 'center',
                    textStyle: {
                        fontWeight: 'normal',
                        fontSize: 16,
                        color: '#F1F1F3'
                    },
                    },
                    tooltip: {
                    trigger: 'axis',
                    formatter:function(params)
                    {
                        var relVal = params[0].name;
                        for (var i = 0, l = params.length; i < l; i++) {
                            relVal += '<br/>'+ params[i].marker + params[i].seriesName + ' : ' + params[i].value+"%";
                        }
                        return relVal;
                    },
                    axisPointer: {
                        type:'line',
                        lineStyle: {
                        color: '#57617B'
                        }            
                    }
                    },
                    legend: {
                    top: 30,
                    type: 'scroll',
                    pageIconColor:'rgb(24,144,255)',
                    pageIconInactiveColor:'#2f4554',
                    icon: 'circle',
                    itemWidth: 14,
                    itemHeight: 10,
                    itemGap: 10,
                    right: '4%',
                    textStyle: {
                        fontSize: 12,
                        color: '#F1F1F3'
                    }
                    },
                    grid: {
                    top: 100,
                    left: '2%',
                    right: '3%',
                    bottom: '4%',
                    containLabel: true
                    },
                    xAxis: [{
                    type: 'category',
                    boundaryGap: false,
                    axisLine: {
                        lineStyle: {
                        color: '#57617B'
                        }
                    },
                    data: this.dateList
                    }],
                    yAxis: [{
                    type: 'value',
                    name: '出勤率',
                    nameTextStyle:{
                        fontStyle : 'normal',
                        fontSize: 16,
                        color:'#FFF'
                    },
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                        color: '#57617B'
                        }
                    },
                    axisLabel: {
                        margin: 10,
                        textStyle: {
                        fontSize: 12
                        },
                        formatter:function(params)
                        { 
                        return params+'%';
                        },
                    },
                    splitLine: {
                        lineStyle: {
                        color: '#57617B'
                        }
                    }
                    }],
                    series: []
                    }

                    const dataList = this.dataList;
                    for (const key in dataList) {
                    if (Object.hasOwnProperty.call(dataList, key)) {
                        optionObj.series.push({
                        name: dataList[key].name,
                        type: 'line',
                        smooth: true,
                        symbol: 'circle',
                        symbolSize: 1,
                        showSymbol: false,
                        lineStyle: {
                        normal: {
                            width: 1
                        }
                        },
                        areaStyle: {
                        normal: {
                            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: `rgba(${this.corlorList[key]}, 0.3)`
                            }, {
                            offset: 0.8,
                            color: `rgba(${this.corlorList[key]}, 0)`
                            }], false),
                            shadowColor: 'rgba(0, 0, 0, 0.1)',
                            shadowBlur: 10
                        }
                        },
                        itemStyle: {
                        normal: {
                            color: `rgba(${this.corlorList[key]})`,
                            borderColor: `rgba(${this.corlorList[key]}, 0.2)`,
                            borderWidth: 12
                        }
                        },
                        data: dataList[key].data
                    })
                    }
                    }
                    //需要返回一个对象
                    return optionObj;
                })());
                
            })
        });
        },
    }
}
</script>
<style scoped> 
#line{
  width: 100%;
  height: calc(100vh - 84px);
  margin: 0 auto;
}
</style>
